
import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:find_friend/common/event_bus.dart';
import 'package:find_friend/pages/login&register/model/shared_user_info.dart';
import 'package:find_friend/pages/mine/mine_background.dart';
import 'package:find_friend/pages/mine/mine_preview_page.dart';
import 'package:flare_flutter/flare_actor.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/pages/mine/mine_head.dart';
import 'package:page_transition/page_transition.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';

import 'mine_mod/mine_modavatar.dart';

class MineHomePage extends StatefulWidget {

  final Function(bool isbottom) onScrollToButtom;
  final double percentDy;

  const MineHomePage({Key key, this.percentDy, this.onScrollToButtom}) : super(key: key);

  @override
  _MineHomePageState createState() => _MineHomePageState();
}

class _MineHomePageState extends State<MineHomePage> with SingleTickerProviderStateMixin{


  SharedUserInfo userInfo = SharedUserInfo();
  int voiceDuration = 0;
  double marginTop = 40;
  bool isplay = false;
  String avatar = "";
  double _currentY = 0;
  Animation<Offset> _animation;
  AnimationController _animationController;
  bool isbottom = false;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 200));
    CurvedAnimation _cureve = CurvedAnimation(curve: Curves.easeInOut, parent: _animationController);
    _animation = Tween<Offset>(begin: Offset(0, 0.05), end: Offset(0, widget.percentDy)).animate(_cureve);
    _initdata();
  }

  _initdata() async {
    final user = await SharedUserInfo.instance();
    RongcloudImPlugin.updateCurrentUserInfo(user.mobile, user.nickname, user.avatar);
    userInfo = user;
    avatar = user.avatar ?? "";
    voiceDuration = user.signvoice?.playtime ?? 0;
    if(mounted) setState(() {});
  }

  void _scrollToBottom() {
    setState(() {
      isbottom = !isbottom;
    });
    EventMineBus.instance.commit(EventMineKeys.HiddenTabbar, isbottom);
    if(widget.onScrollToButtom != null) widget.onScrollToButtom(isbottom);
  }
  
  Widget _createMineView(Size size) {
    return GestureDetector(
              onPanUpdate: (detail){
                if(!isbottom && detail.delta.dy < 0) return;
                _currentY += detail.delta.dy.abs();
              },
              onPanEnd: (detail){
                if(_currentY < 10) return;
                _animationController.isCompleted ? _animationController.reverse() : _animationController.forward();
                _currentY = 0;
                _scrollToBottom();
              },
              child: SingleChildScrollView(
                physics: NeverScrollableScrollPhysics(), // 
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        SizedBox(width: 48,),
                        IconButton(
                          padding: const EdgeInsets.only(top: 20),
                          onPressed: (){
                            _animationController.isCompleted ? _animationController.reverse() : _animationController.forward();
                            _scrollToBottom();
                          },
                          icon: Transform.rotate(angle: isbottom ? pi : pi * 2, child: Image.asset("assets/xiahua.png"),)
                        ),
                        Opacity(
                          opacity: isbottom ? 0 : 1,
                          child: InkWell(
                            onTap: (){
                              if(isbottom) {
                                EventMineBus.instance.commit(EventMineKeys.AlertDressupWidget, null);
                              } else {
                                Navigator.push(context, PageTransition(
                                  child: MinePreviewPage(mobile: userInfo.mobile),
                                  curve: Curves.ease,
                                  alignment: Alignment.bottomCenter,
                                  type: PageTransitionType.size
                                ));
                              }
                            },
                            child: Container(
                              width: 50,
                              height: 40,
                              alignment: Alignment.center,
                              margin: const EdgeInsets.only(right: 8),
                              decoration: BoxDecoration(
                                image: DecorationImage(image: AssetImage("assets/my-yulan.png"), fit: BoxFit.fitWidth)
                              ),
                              child: Text("预览", style: instanceTextStyle(12, APP_font_black)),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Stack(
                      overflow: Overflow.visible,
                      children: [
                        Container(
                          decoration: BoxDecoration(
                            boxShadow: [
                              BoxShadow(
                                color: Colors.black.withOpacity(0.5),
                                spreadRadius: 2,
                                blurRadius: 7,
                                offset: Offset(0, 3), // changes position of shadow
                              ),
                            ]
                          ),
                          child: PhysicalModel(
                            color: Colors.transparent,
                            borderRadius: BorderRadius.circular(10),
                            clipBehavior: Clip.antiAlias,
                            child: CachedNetworkImage(
                                placeholder: (context, url) => Container(color: Colors.black12,),
                                imageUrl: userInfo.longback ?? "",
                                width: size.width,
                                height: size.height,
                                fit: BoxFit.cover,
                              ),
                            ),
                        ),
                        Positioned(
                          top: -20,
                          left: 10,
                          child: GestureDetector(
                            onTap: () async {
                              var result = await Navigator.push<bool>(
                                context, 
                                CupertinoPageRoute(builder: (context) => MineModAvatarPage(avatar: userInfo.avatar,))
                              );
                              if(result == true) _initdata();
                            },
                            child: PhysicalModel(
                                color: Colors.transparent,
                                shape: BoxShape.circle,
                                clipBehavior: Clip.antiAlias,
                                shadowColor: Colors.black,
                                elevation: 2,
                                child: Image.network(avatar,
                                      height: 80.w,
                                      width: 80.w,
                                      fit: BoxFit.cover,
                                    ),
                              ),
                          ),
                        ),

                        // 个人资料
                        MineHead(hiddenSignVoice: isbottom,),

                        // 签到
                        Positioned(
                          right: 10,
                          top: 12.5,
                          child: Offstage(
                            offstage: isbottom,
                            child: Column(
                              children: [
                                InkWell(
                                  onTap: (){
                                    Navigator.pushNamed(context, "/minesign", arguments: userInfo.mobile);
                                  },
                                  child: Container(
                                    padding: const EdgeInsets.symmetric(horizontal: 19, vertical: 4.5),
                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(
                                      image: DecorationImage(image: AssetImage("assets/my-qiandao.png"),fit: BoxFit.fill)
                                    ),
                                    child: Text("签到", style: instanceTextStyle(11, APP_font_black),),
                                  ),
                                ),
                                SizedBox(height: 10,),
                                Text("粉丝：1233", style: instanceTextStyle(10, Colors.white),)
                              ],
                            ),
                          ),
                        ),

                        // 更改照片墙
                        Positioned(
                          right: 10,
                          top: 50,
                          child: GestureDetector(
                            onTap: () async {
                              if(isbottom) return;
                              bool isok = await push(context, MineBackgroundPage());
                              if(isok) _initdata();
                            },
                            child: Container(
                              width: 66,
                              height: 66,
                              color: Colors.transparent,
                            ),
                          ),
                        ),
                      ]
                    ),
                  ],
                ),
              ),
            );
  }

  // double compleOrginY() {
  //   double res;
  //   if(!scrolldirection) { // 向下滑动
  //     res = 40 + (_bottomheight - 40) * _animation.value;
  //   } else {  // 向上滑动
  //     res = 40 + _bottomheight * _animation.value;
  //   }
  //   marginTop = res;
  //   return res;
  // }
  
  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return SlideTransition(
      position: _animation,
      child: _createMineView(size),
    );
    // return 
  }
}

class MineFlrTestPlatWidget extends StatelessWidget {

  final bool isplay;
  final int duration;
  final EdgeInsets margin;
  final EdgeInsets padding;
  final double width;
  final double height;
  final Color color;
  final String audioImgBackName;

  const MineFlrTestPlatWidget({
    Key key, 
    this.isplay, 
    this.duration, 
    this.margin, 
    this.padding, 
    this.width, 
    this.height,
    this.color,
    this.audioImgBackName
  }) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Container(
      width: width,
      height: height,
      margin: margin,
      padding: padding,
      decoration: BoxDecoration(
        image: DecorationImage(image: AssetImage(audioImgBackName),fit: BoxFit.fill)
      ),
      child: Stack(
        alignment: Alignment.centerRight,
        children: [
          Positioned(
            left: -10,
            child: ClipRect(
              clipper: MyClipper(),
              child: Container(
                height: 40.h,
                width: 50.w,
                child: FlareActor("assets/flr/record.flr", color: color ?? Colors.white, alignment:Alignment.center, fit:BoxFit.fitWidth, animation:isplay ? "record" : "stop")
              ),
            ),
          ),
          Positioned(
            right: 9,
            child: Text("$duration‘‘", style: instanceTextStyle(14, color ?? Colors.white),)
          )
        ],
      ),
  );
  }
}


class MyClipper extends CustomClipper<Rect> {
  @override
  Rect getClip(Size size) => Rect.fromLTWH(19.0, 10.0, 50.0.w, 30.0.h);

  @override
  bool shouldReclip(CustomClipper<Rect> oldClipper) => false;
}